$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'goods/goodsattribute/list',
        datatype: "json",
        colModel: [			
			{ label: '规格id', name: 'attributeId', index: 'attribute_id', width: 50, key: true },
			{ label: '属性名称', name: 'attributeName', index: 'attribute_name', width: 80 },
            {
                label: '属性类型', name: 'attributeType', index: 'attribute_type', width: 80,
                formatter: function (value, options, row) {
                    if (value == 'normal') {
                        return '普通';
                    } else if (value == 'material') {
                        return '材料';
                    } else if (value == 'craft') {
                        return '工艺';
                    } else if (value == 'design') {
                        return '设计';
                    }
                }
            },
			// { label: '规格类型', name: 'classify', index: 'classify', width: 80,
             //    formatter: function (value, options, row) {
             //        if (value == '1') {
             //            return '页数';
             //        } else if (value == '2') {
             //            return '尺寸';
             //        }else if (value == '3') {
             //            return '数字';
             //        }else if (value == '4') {
             //            return '图片';
             //        }else if (value == '5') {
             //            return '文字';
             //        }else if (value == '6') {
             //            return '大纸';
             //        }
             //    }},
            { label: '绑定分类id', name: 'categoryId', index: 'attribute_sort', width: 80 },
            { label: '绑定分类名称', name: 'categoryName', index: 'attribute_sort', width: 80 },
            { label: '属性排序', name: 'attributeSort', index: 'attribute_sort', width: 80 },
			{ label: '创建人', name: 'createName', index: 'create_name', width: 80 }, 			
			{ label: '创建时间', name: 'createTime', index: 'create_time', width: 80 },
            {
                label: '操作', name: 'operation', width: 80,
                formatter: function (value, options, row) {
                    var html = '<a href="#" onclick="showValues('+ row.attributeId +')" style="margin:0 auto;" class="dropdown-toggle" style="" data-toggle="dropdown">查看</a>';
                    return html;
                }
            }
        ],
		viewrecords: true,
        height: 560,
        rowNum: 20,
		rowList : [20,35,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            // root: "page.list",
            // page: "page.currPage",
            // total: "page.totalPage",
            // records: "page.totalCount"
            root: "page.records",
            page: "page.current",
            total: "page.pages",
            records: "page.total"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});
function showValues(attributeId){
	vm.showValues(attributeId);
}

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "categoryId",
            pIdKey: "parentCategoryId",
            rootPId: -1
        },
        key: {
            name: "categoryName",
            url:"nourl"
        }
    }
};
var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		goodsAttribute: {categoryName:''},
        goodsOptionList: [],
        option : {},
        q:{
            attributeId:"",
            attributeName:"",
            attributeType:""
        }
	},
	methods: {
        //加载商品分类树
        getGoodsCategory: function(){
            $.get(baseURL + "goodsCategory/goodscategory/select", function(r){
                ztree = $.fn.zTree.init($("#goodsCategoryTree"), setting, r.goodsCategoryEntityList);
                var node = ztree.getNodeByParam("categoryId", vm.goodsAttribute.categoryId);
                // if(node != null){
                //     ztree.selectNode(node);
                //     vm.goodsCategory.parentName = node.categoryName;
                // }
            })
        },
        //点击弹窗三级分类选择
        goodsCategoryTree: function(){
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择商品分类",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#goodsCategoryLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级菜单
                    vm.goodsAttribute.categoryId = node[0].categoryId;
                    vm.goodsAttribute.categoryName = node[0].categoryName;
                    layer.close(index);
                }
            });
        },
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.goodsAttribute = {categoryName:'请选择分类',attributeType:'normal',classify:''};
            vm.goodsOptionList = [];
            vm.option = {};
            vm.getGoodsCategory();
		},
		//获得规格属性值
        showValues: function(attributeId){
            vm.loadAttributeValues(attributeId);
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "规格值详细",
                area: ['800px', '400px'],
                shadeClose: false,
                content: jQuery("#optionLayer"),
                btn: ['确认'],
            });

		},
        deleteOption:function(optionId,index){
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "goods/goodsoption/flagDelete/"+optionId,
                    contentType: "application/json",
                    data: JSON.stringify(optionId),
                    success: function(r){
                        if(r.code === 0){
                            alert("删除成功")
                            vm.goodsOptionList.splice(index,1);
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
		},
        //新增规格的删除规格值,不存入数据库
        delOption:function(index){
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
            vm.goodsOptionList.splice(index,1);
        },
        //更新规格值
        updateOption:function(optionId,optionName,optionValue){
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
            //弹窗layer
            vm.option.optionId = optionId;
            vm.option.optionName = optionName;
            vm.option.optionValue = optionValue;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "修改规格值",
                area: ['800px', '400px'],
                shadeClose: false,
                content: jQuery("#addOptionLayer"),
                btn: ['确认', '取消'],
                btn1:function(index){
                    //先判断一下是否有重复值
                    for(var i = 0;i<vm.goodsOptionList.length;i++){
                        if(vm.goodsOptionList[i].optionName == vm.option.optionName && vm.goodsOptionList[i].optionId != vm.option.optionId){
                            alert("请不要重复添加!")
                            return;
                        }
                    }
                    //更新规格值
                    $.ajax({
                        type: "POST",
                        url: baseURL + "goods/goodsoption/update",
                        contentType: "application/json",
                        data: JSON.stringify(vm.option),
                        success: function(r){
                            if(r.code === 0){
                                vm.loadAttributeValues(vm.goodsAttribute.attributeId);
                                layer.close(index)
                            }else{
                                alert(r.msg);
                            }
                        }
                    });

                }
            });
        },
		//加载规格属性值
		loadAttributeValues:function(attributeId){
            $.ajax({
                type: "POST",
                url: baseURL + "goods/goodsoption/getValues/"+attributeId,
                contentType: "application/json",
                data: JSON.stringify(attributeId),
                success: function(r){
                    if(r.code === 0){
                        vm.goodsOptionList = r.goodsOptionList;
                    }else{
                        alert(r.msg);
                    }
                }
            });
		},
        //添加规格属性值
        addOption:function(attributeId){
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "添加规格值",
                area: ['800px', '400px'],
                shadeClose: false,
                content: jQuery("#addOptionLayer"),
                btn: ['确认','取消'],
                btn1: function (index) {
                    //先判断一下是否有重复值
                    for(var i = 0;i<vm.goodsOptionList.length;i++){
                        if(vm.goodsOptionList[i].optionName == vm.option.optionName){
                            alert("请不要重复添加!")
                            return;
                        }
                    }
                    vm.option.attributeId = vm.goodsAttribute.attributeId;
                    $.ajax({
                        type: "POST",
                        url: baseURL + "goods/goodsoption/save",
                        contentType: "application/json",
                        data: JSON.stringify(vm.option),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                //添加规格值进goodsOptionList
                                vm.loadAttributeValues(attributeId)
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        newlyOption:function(){
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
            vm.goodsOptionList.push({optionName:'',optionValue:''})
        },
		update: function (event) {
			var attributeId = getSelectedRow();
			if(attributeId == null){
				return ;
			}
            vm.getGoodsCategory();
            vm.loadAttributeValues(attributeId);
			vm.showList = false;
            vm.title = "修改";
            vm.getInfo(attributeId);
            vm.option= {optionName:'',optionValue:''};
		},
		saveOrUpdate: function (event) {
            if (vm.goodsAttribute.dateFlag == 1){
                alert("老数据不让修改!")
                return;
            }
			var url = vm.goodsAttribute.attributeId == null ? "goods/goodsattribute/save" : "goods/goodsattribute/update";
			vm.goodsAttribute.goodsOptionList = vm.goodsOptionList;
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.goodsAttribute),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							//重新加载跳转到列表页面
                            vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},

		del: function (event) {
			var attributeIds = getSelectedRows();
			if(attributeIds == null){
				return ;
			}
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "goods/goodsattribute/delete",
                    contentType: "application/json",
				    data: JSON.stringify(attributeIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(attributeId){
			$.get(baseURL + "goods/goodsattribute/info/"+attributeId, function(r){
                vm.goodsAttribute = r.goodsAttribute;
                if(!isBlank(r.goodsCategory)){
                    vm.goodsAttribute.categoryName = r.goodsCategory.categoryName;
                }

            });
		},
        reset:function(){
            vm.q.attributeId = '';
            vm.q.attributeName = "";
            vm.q.attributeType = "";
        },
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page,
                postData:{
                    attributeId:vm.q.attributeId,
                    attributeName:vm.q.attributeName,
                    attributeType:vm.q.attributeType
                }
            }).trigger("reloadGrid");
		},
        // changeOptionName:function(){
        //     //若不影响计价
        //     if(!vm.goodsAttribute.influenceCraftType){
        //         vm.goodsOptionList[index].optionValue = vm.goodsOptionList[index].optionName;
        //     }
        //
        // }
	}
});